package com.bkgy.modularbx.commonbx.impl;

import com.bkgy.config.BusinessException;
import com.bkgy.modularbx.commonbx.BxCommonService;
import com.bkgy.modularbx.commonbx.dao.BxCommonDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class BxCommonServiceImpl implements BxCommonService {

    @Autowired
    private BxCommonDao commonDao;

    private static final Integer DEFAULT_MAX_INDOCNO_BEGIN = 900000000;

    @Override
    public Integer getMaxIndocno(String type) {
        try {
            Optional<Integer> maxIndocno = Optional.ofNullable(findMaxIndocno(type));
            if (maxIndocno.isPresent()) {
                return maxIndocno.map(max ->
                        max >= DEFAULT_MAX_INDOCNO_BEGIN
                                ? max + 1
                                : DEFAULT_MAX_INDOCNO_BEGIN + max + 1
                ).orElse(null);
            } else {
                return null;
            }
        } catch (Exception e) {
            throw new BusinessException("添加失败");
        }
    }

    public Integer findMaxIndocno(String type) {
        if ("DATA_DICTIONARY".equals(type)) {
            return commonDao.findMaxIndocno_dataDictionary();
        } else if ("DATA_COLLECTION".equals(type)) {
            return commonDao.findMaxIndocno_dataCollection();
        } else if ("PROCESS_RULE".equals(type)) {
            return commonDao.findMaxIndocno_processRuleLibrary();
        } else if ("RULE_EDIT".equals(type)) {
            return commonDao.findMaxIndocno_ruleEdit();
        } else if ("THEME_DATA".equals(type)) {
            return commonDao.findMaxIndocno_themeData();
        }
        return null;
    }

}
